<template>
  <el-container>
    <el-main>
      <el-form ref="productForm" :model="form" label-width="90px">
        <div style="display: flex">
          <div>
            <el-form-item label="活动名称" prop="name" style="width: 570px"
                          :rules="{ required: true, message: '请输入商品名称', trigger: 'blur' }">
              <el-input v-model="form.name"/>
            </el-form-item>
            <el-form-item label="活动说明" prop="subTitle" style="width: 570px">
              <el-input v-model="form.subTitle"/>
            </el-form-item>
            <el-row>
              <el-form-item label="起止日期" prop="endDate"
                            :rules="{ required: true, message: '请选择起止日期', trigger: 'blur' }">

                <el-date-picker
                  v-model="form.endDate"
                  type="datetimerange"
                  style="width: 480px"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :picker-options="pickerOptions">
                </el-date-picker>
              </el-form-item>
            </el-row>
          </div>

        </div>

        <div style="display: flex">
          <el-form-item label="砍杀价" style="width: 185px" prop="price"
                        :rules="{ required: true, message: '请输入团购价', trigger: 'blur' }">
            <el-input v-model="form.price" placeholder="请输入价格"/>
          </el-form-item>
          <el-form-item v-if="form.type==1" label="奖励金" prop="point" style="width: 185px"
                        :rules="{ required: true, message: '请输入奖励金', trigger: 'blur' }">
            <el-input v-model="form.point" placeholder="请输入奖励金"/>
          </el-form-item>
          <el-form-item label="邀请人数" style="width: 185px" prop="bargainNum"
                        :rules="{ required: true, message: '请输入邀请人数', trigger: 'blur' }">
            <el-input v-model="form.bargainNum" placeholder="请输入人数"/>
          </el-form-item>
        </div>

        <!--<div style="display: flex">-->
          <!--<el-form-item label="机器人数" style="width: 200px" prop="robotNum"-->
                        <!--:rules="{ required: true, message: '请输入有效单数', trigger: 'blur' }">-->
            <!--<el-input v-model="form.robotNum" placeholder="请输入机器人数"/>-->
          <!--</el-form-item>-->
          <!--<el-form-item label="超时时长" style="width: 185px" prop="duration"-->
                        <!--:rules="{ required: true, message: '超时时长(分钟数)', trigger: 'blur' }">-->
            <!--<el-input v-model="form.duration" placeholder="超时时长(分钟数)"/>-->
          <!--</el-form-item>-->
        <!--</div>-->


        <el-tabs>
          <!--tab1-->
          <el-tab-pane label="活动商品">
            <!-- <div style="width: 100%;display: flex;justify-content: flex-end;align-items: center">
              <el-button type="primary" style="margin-bottom: 10px;" @click="addProduct" >添加规格</el-button>
            </div> -->
            <!--商品规格-->
            <el-row style="display: flex;  position: relative;margin-left: 90px">
              <span class="el-icon-plus" style="position: absolute; top: 69px;left: -25px; color: #409EFF;"
                    @click="addProduct"/>
              <el-col :span="16">
                <el-table
                  :data="productList"
                  border
                  stripe
                  style="width: 100%;"
                >
                  <el-table-column
                    label="商品名称"
                    min-width="320"
                  >
                    <template slot-scope="scope">
                      <el-select style="width: 100%" value-key="id" v-model="scope.row.name" filterable
                                 placeholder="请选择" @focus="selectIndex(scope)" @change="selectClick(scope)" :filter-method="productMethod">
                        <el-option
                          v-for="(item,index) in listForm"
                          :key="item.id"
                          :label="item.name"
                          :value="item"
                        >
                        </el-option>
                        <div style="display: flex;width: 100%;position: absolute;bottom: 0">
                          <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                          <div class="elOption" @click="toAddProduct">搜索商品</div>
                          <div class="elOption1" @click="toSearchProduct">新增商品</div>
                        </div>
                        <div style="height: 30px"></div>
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="商品图片"
                    width="80"
                    align="center"
                    prop="thumbnail"
                  >
                    <template slot-scope="{row}">
                      <img :src="row.thumbnail" v-if="row.thumbnail!=''" style="width: 50px;height: 50px">
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="数量"
                    width="80"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.quantity"/>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="规格"
                    min-width="220"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.spec"/>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="单位"
                    width="120"
                  >
                    <template slot-scope="{row}">
                      <el-input v-model="row.unit"/>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="操作"
                    width="80"
                  >
                    <template v-if="!row.isList" slot-scope="{row}">
                      <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                        <a @click="delProduct(row)">
                          <i style="color: #F56C6C" class="el-icon-delete"/>
                        </a>
                      </el-tooltip>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
            </el-row>
          </el-tab-pane>

          <el-tab-pane label="详情">
            <div class="menu-wrapper">
              <tinymce v-model="article.content" :height="300" :width="950"/>
              <el-row>
                <div class="photo-content">
                  <div style="margin-top: 20px">
                    <span style="font-size: 18px;color:#409EFF;">轮播图</span>
                  </div>
                </div>
                <multi-upload v-model="article.productMeta.images"/>
              </el-row>
              <el-row>
                <div class="photo-content">
                  <div style="margin-top: 20px;">
                    <span style="font-size: 18px;color:#409EFF;margin: 10px 0;">视频介绍</span>
                  </div>
                </div>
                <el-col :span="8">
                  <video-upload v-model="article.productMeta.video"/>
                </el-col>
              </el-row>
            </div>
          </el-tab-pane>
        </el-tabs>
        <el-form-item>
          <el-button style="margin-top: 30px" type="primary" :loading="clicked" @click="saveBargain('productForm')">
            &nbsp&nbsp完 成&nbsp&nbsp
          </el-button>
        </el-form-item>
      </el-form>
    </el-main>
    <el-dialog
      title="新增商品"
      :visible.sync="procuctVisible"
      width="950px"
      v-el-drag-dialog
      :before-close="productClose">
      <div style="height: 65vh;overflow: auto;position: relative;">
        <productAdd :type="productType" @saveProduct="saveProduct"></productAdd>
      </div>
    </el-dialog>
    <el-dialog
      title="搜索商品"
      :visible.sync="orderVisible"
      width="950px"
      v-el-drag-dialog
      :before-close="orderClose">
      <div style="position: relative;">
        <productTable ref="productList" @doubleClick="doubleClick" @addClick="addClick"></productTable>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
  import productAdd from '@/views/product/add'
  import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
  import productTable from '@/components/ProductList/productList'
  import MultiUpload from '@/components/Upload/multiUpload'
  import VideoUpload from '@/components/Upload/videoUpload'
  import Tinymce from '@/components/Tinymce'
  import { EventBus } from '@/api/eventBus'
  import SingleUpload from '@/components/Upload/singleUpload'
  import { save } from '@/api/bargainBuy'
  import { list } from '@/api/product'
  import permission from '@/directive/permission'
  export default {
    name: 'bargainBuy-add',
    directives: {elDragDialog,permission},
    data() {
      return {
        listForm: [],
        productList: [{
          name: '',
          productId: '',
          quantity: 0,
          spec: '',
          thumbnail: '',
          unit: ''
        }],
        index:'',
        form: {
          thumbnail: '',
          duration:'',
          subTitle:'',
          robotNum:0,
          type: '1',
          endDate: '',
          point: 0,
          name: '',
          beginDate: '',
          bargainNum: '',
          price: '',
          marketPrice: ''
        },
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() + 86400000 < Date.now()
          }
        },
        orderVisible:false,
        productType: 'order',
        procuctVisible:false,
        article: {
          productMeta: {
            images: [],
            video: '',
            label: ''
          },
          content: ''
        },
        clicked: false
      }
    },
    created() {
      this.setAddClickHeight()
      this.loadProduct('')
    },
    components: { productAdd, productTable, MultiUpload, VideoUpload, Tinymce, SingleUpload },
    methods: {
      toAddProduct(){
        this.orderVisible = true;
      },
      orderClose() {
        this.orderVisible = false;
        this.$refs.productList.cancelClick();
      },
      toSearchProduct(){
        this.procuctVisible = true;
      },
      saveProduct(data) {

        this.listForm.splice(0, 0, data);
        // this.productList[this.tableIndex] = data;
        this.procuctVisible = false;
      },
      selectIndex(data){
        this.index=data.$index
      },
      doubleClick(val) {

        if (this.productList.length==1&&this.productList[0].name==''){
          this.productList[0].productId=val.id
          this.productList[0].name=val.name
          this.productList[0].quantity=1
          this.productList[0].thumbnail=val.thumbnail
          this.productList[0].spec=val.spec1 + val.spec2
          this.productList[0].unit=val.unit
        }else if (this.productList[this.productList.length-1].name==''){
          this.productList[this.productList.length-1].productId=val.id
          this.productList[this.productList.length-1].name=val.name
          this.productList[this.productList.length-1].quantity=1
          this.productList[this.productList.length-1].thumbnail=val.thumbnail
          this.productList[this.productList.length-1].spec=val.spec1 + val.spec2
          this.productList[this.productList.length-1].unit=val.unit
        }else{
          this.productList[this.index].productId=val.id
          this.productList[this.index].name=val.name
          this.productList[this.index].quantity=1
          this.productList[this.index].thumbnail=val.thumbnail
          this.productList[this.index].spec=val.spec1 + val.spec2
          this.productList[this.index].unit=val.unit
        }
        this.searchSame()
        this.orderVisible=false
        this.setAddClickHeight()
      },
      addClick(data) {
        var _this = this
        if (this.productList.length==1&&this.productList[0].name==''){
          var list=[]
          data.forEach(item=>{
            var goodsDetails = {
              productId: item.id,
              name: item.name,
              quantity:1,
              thumbnail:item.thumbnail,
              spec: item.spec1 + item.spec2,
              unit: item.unit
            }
          list.push(goodsDetails)
          });
          _this.productList=list
          _this.productList[0].quantity=1
        }else{
          data.forEach(item=>{
            var goodsDetails = {
              productId: item.id,
              name: item.name,
              quantity:1,
              thumbnail:item.thumbnail,
              spec: item.spec1 + item.spec2,
              unit: item.unit
            }
            _this.productList.push(goodsDetails)
          });
        }
        this.orderVisible=false
        this.searchSame()
        this.setAddClickHeight()
      },
      addProduct() {
        var product = {
          name: '',
          quantity: 0,
          spec: '',
          thumbnail: '',
          unit: ''
        }
        this.productList.push(product)
        this.setAddClickHeight()
      },
      productMethod(query) {
        this.loadProduct(query)
      },
      delProduct(row) {
        var index = this.productList.indexOf(row)
        if (index !== -1) {
          this.productList.splice(index, 1)
        }

        this.setAddClickHeight()
      },
      loadProduct(query) {
        var param = new URLSearchParams()
        param.append('name', query)
        list(param).then(res => {
          this.listForm = res.data.data
        })
      },
      productClose() {
        this.procuctVisible = false;
      },
      selectClick(data) {
        this.productList[data.$index].spec = data.row.name.spec1
        this.productList[data.$index].productId = data.row.name.id
        this.productList[data.$index].quantity = 1
        this.productList[data.$index].thumbnail = data.row.name.thumbnail
        this.productList[data.$index].unit = data.row.name.unit
        this.productList[data.$index].name = data.row.name.name
        this.searchSame()
      },
      searchSame(){
        var newList={}
        newList=this.productList[this.productList.length-1]
        if (this.productList.length>1){
          for (var i=0;i<this.productList.length-1;i++){
            if (this.productList[i].productId===newList.productId){
              this.productList[i].quantity=this.productList[i].quantity+1
              this.productList.pop()
            }
          }
        }
        this.productList = this.productList.filter(item => {
          return item.name!=''
        })
      },
      setAddClickHeight() {
        setTimeout(() => {
          // 获取表头的高度
          const tableTopHeight = document.querySelector('.el-table__header-wrapper').offsetHeight
          // 获取一行表格高度
          const tableHeight = document.querySelector('.el-table__row').offsetHeight
          // 获取添加按钮样式
          const addClickStyle = document.querySelector('.el-icon-plus')
          // 获取添加按钮高度
          const addClickHeight = addClickStyle.offsetHeight
          // 设置添加按钮的位置
          const moveHeight = tableTopHeight + ((this.productList.length - 1) * tableHeight) + ((tableHeight - addClickHeight) / 2)
          console.log(tableTopHeight, 'tableTopHeight')
          console.log(tableHeight, 'tableHeight')
          console.log(moveHeight, 'moveHeight')
          addClickStyle.style.top = moveHeight + 'px'
        }, 100)
      },
      saveBargain(form) {

        this.$refs[form].validate((valid) => {
          if (valid) { // 校验表单
            this.clicked = true
            let newDate = this.form.endDate
            if (newDate.length > 0) {
              this.form.beginDate = newDate[0]
              this.form.endDate = newDate[1]
            }
            this.productList = this.productList.filter(item => {
              return item.name!=''
            })

            var product = {
              type: this.form.type,
              endDate: this.form.endDate,
              beginDate: this.form.beginDate,
              point: this.form.point*100,
              thumbnail: this.form.thumbnail,
              duration:this.form.duration,
              robotNum:this.form.robotNum,
              status: 0,
              subTitle:this.form.subTitle,
              periodNum:0,
              name: this.form.name,
              bargainNum: this.form.bargainNum,
              price: this.form.price,
              marketPrice: this.form.marketPrice,
              itemList: this.productList,
              article: {
                productMeta: {},
                content: this.article.content
              }

            }
            if (product.thumbnail==''){
              this.$message({
                message: '活动主图不能为空',
                type: 'warning'
              });
              this.clicked=false
              return
            }
          if (parseInt(product.robotNum)>parseInt(product.bargainNum)){
              this.$message({
                message: '机器人数量不能大于邀请人数',
                type: 'warning'
              });
              this.clicked=false
              return
            }
            product.article.productMeta = this.article.productMeta
            console.log(product)
            save(product).then(res => {
              this.clicked = false
              EventBus.$emit('bargainBuy-add', res.data[0])
              this.$store.dispatch('tagsView/delView', this.$route).then(({ visitedViews }) => {
                this.$router.push({
                  path: '/bargainBuy/list'
                })
              })// 关闭当前tab回到列表
            }).catch(error => {
              this.clicked = false
            })

          }
        })

      }
    }
  }
</script>

<style scoped>
  /deep/ .el-input__inner {
    padding: 0 5px;
  }

  .photo-content {
    width: 100%;
    display: flex;
    align-items: flex-end;
    border-top: 1px #eee solid;
    margin-bottom: 20px;
    margin-top: 10px;
  }
  /deep/.el-upload__tip{
    display: none;
  }
  /deep/.el-upload-list--picture {
    position: absolute;
    width: 110px;
  }
  .elOption1{
    background-color: #409EFF;
    color:white ;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 25%;
    height: 40px
  }
  .elOption{
    background-color: #909399;
    color:white ;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 25%;
    height: 40px
  }
  /deep/ .el-upload--picture-card {
    width: 50px !important;
    height: 50px !important;
    line-height: 50px !important;
    text-align: center;
  }
</style>
